package com.example.myBlogTest.service;

import cn.hutool.crypto.SecureUtil;
import com.example.myBlogTest.dto.UserRequest;
import com.example.myBlogTest.dto.UserResponse;
import com.example.myBlogTest.entity.User;
import com.example.myBlogTest.exception.NotFoundException;
import com.example.myBlogTest.exception.SaveObjectException;
import com.example.myBlogTest.mapper.UserMapper;
import com.example.myBlogTest.repository.UserRepository;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User getById(Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        return user;
    }

    public UserResponse findByUsernameAndPassword(String username, String password) {
        User foundUser = userRepository.findByUsername(username);
        if(foundUser == null) {
            throw new NotFoundException("用户不存在");
        }
        if(!foundUser.getPassword().equals(SecureUtil.md5(password))) {
            throw new NotFoundException("密码不正确");
        }
        return UserMapper.convertUserToUserResponse(foundUser);
    }

    public UserResponse saveUser(UserRequest userRequest) {
        User foundUser = userRepository.findByUsernameOrEmail(userRequest.getUsername(), userRequest.getEmail());
        if(foundUser != null) {
            if(foundUser.getUsername().equals(userRequest.getUsername())) {
                throw new SaveObjectException("用户名已存在");
            }
            if(foundUser.getEmail().equals(userRequest.getEmail())) {
                throw new SaveObjectException("邮箱已注册");
            }
        }
        User savedUser = userRepository.save(UserMapper.convertUserRequestToUser(userRequest));
        return UserMapper.convertUserToUserResponse(savedUser);
    }
}
